package math
{
	import flash.display.DisplayObject;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.geom.Vector3D;
	
	import kim.math.ui.Photo;

	public class Circle extends Sprite
	{
		
		private var R:int=180;//圆半径
		private var container:Sprite=new Sprite();//创建容器
		private var num:int=10;//边数
		private var angle:Number=2*Math.PI/num;//每一个角度
		private var perangle:Number=(num-2)*Math.PI/num;//多边形内角和除以边数
		private var list:Array=new Array();//用于图片管理的数组
		private var speedx:Number=0;
		private var speedy:Number=0;
		public function Circle(centerX:Number, centerY:Number, _stage:DisplayObject)
		{
			addChild(container);
			container.x=centerX;
			container.y=centerY;
			container.z=0;
			createSphere();//创建球体分布
			addEventListener(Event.ENTER_FRAME,Run);
			_stage.addEventListener(MouseEvent.MOUSE_MOVE,onMove);
		}
		
		private function createSphere():void
		{
			
			for (var j:int=0; j<num; j++)
			{
				var myphoto:Photo=new Photo();
				container.addChild(myphoto);
				list.push(myphoto);
				myphoto.x=R*Math.cos(j*angle);//采用圆的轨迹分布对圆进行分布
				myphoto.z=R*Math.sin(j*angle);
				myphoto.y=0;
				myphoto.rotationY= (j*perangle) * (180/Math.PI)+90;//偏移角度计算
			}
		}
		
		//当鼠标与中心点产生一段距离的时候
		private function onMove(event:MouseEvent):void
		{
			speedx=(mouseX-container.x)*0.01;
			speedy=(mouseY-container.y)*0.01;
			
		}
		
		private function Run(event:Event):void
		{
			container.rotationY+=speedx;
			container.rotationX+=speedy;
			sortZ();
		}
		
		
		//深度排序管理
		private function sortZ():void
		{
			list.sort(depthSort);
			
			for (var i:int=0; i<list.length; i++)
			{
				var myimage:Photo=list[i];
				container.setChildIndex(myimage,i);
				
			}
			
		}
		//摘录make thing move 姐妹篇一个管理方法 
		private function depthSort(objA:DisplayObject,objB:DisplayObject):int
		{
			var posA:Vector3D=objA.transform.matrix3D.position;
			posA=container.transform.matrix3D.deltaTransformVector(posA);
			
			var posB:Vector3D=objB.transform.matrix3D.position;
			posB=container.transform.matrix3D.deltaTransformVector(posB);
			return posB.z-posA.z;
		}
	}
	
}